<template>
  <a-spin :spinning="spinning">
    <page-header-wrapper
      v-if="!submitSuccess"
      :title="`申请编号：${editData.ApplyNO || ''}`"
      :tabList="tabList"
      :tab-active-key="activeKey"
      :tab-change="handleTabChange"
    >
      <template v-slot:extra>
        <a-button type="primary" shape="round" @click="handleSubmit">确认修改</a-button>
        <a-button type="" shape="round" @click="handleClose">取消修改</a-button>
      </template>
      <div v-if="!spinning">
        <info v-show="activeKey === 'info'" ref="info" :data="editData" />
        <!-- <report v-show="activeKey === 'report'" ref="report" :data="editData" /> -->
      </div>
      <div v-show="activeKey === 'report' && $store.state.user.sfsq != '是'">
        <report v-if="tabClick[1]" />
      </div>
      <div v-show="activeKey === 'report' && $store.state.user.sfsq == '是'">
        <editreport ref="report" :data="editData" v-show="tabClick[1]" />
      </div>
      <div v-show="activeKey === 'infoLog'">
        <infoLog v-if="tabClick[2]" />
      </div>
      <div v-show="activeKey === 'houseLog'">
        <houseLog v-if="tabClick[3]" />
      </div>
    </page-header-wrapper>
    <transition enter-active-class="zoom_in">
      <a-card :bordered="false" v-if="submitSuccess">
        <a-result status="success" title="修改成功" sub-title="保障用户信息已修改。">
          <template #extra>
            <y-button type="success" @click="handleClose"> 关闭当前页面 </y-button>
          </template>
        </a-result>
      </a-card>
    </transition>
  </a-spin>
</template>

<script>
import houseLog from './components/houseLog'
import infoLog from './components/infoLog'
import info from '@/views/CommunityReviewManagement/applicationForm/infoCommunity'
import report from './components/report'
import editreport from './components/editreport'
import { getNewProposerbyID, getSubsistenceAllowance } from '@/api/common'
import { postApplication, getHousesCount } from '@/api/communityReviewManagement'
import cloneDeep from 'lodash.clonedeep'
export default {
  name: 'cityComplexInquireList',
  components: {
    houseLog,
    infoLog,
    info,
    report,
    editreport,
  },
  data() {
    return {
      tabList: [
        { key: 'info', tab: '保障用户基本信息' },
        { key: 'report', tab: '调查报告与机构意见' },
        { key: 'infoLog', tab: '信息变更记录' },
        { key: 'houseLog', tab: '房屋分配记录' },
      ],
      browserCacheObj: {},
      activeKey: 'info',
      tabClick: [true, false, false, false],
      editData: {},
      submitSuccess: false,
      spinning: false,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.spinning = true
      // this.browserCacheObj = JSON.parse(localStorage.getItem('browserCacheEdit'))
      getNewProposerbyID({
        // ProposerID: this.$route.params.id,
        ProposerID: JSON.parse(localStorage.getItem('browserCacheEdit')).id,
      })
        .then((res) => {
          res.RegionNo = Number(res.RegionNo)
          res.TownshipNo = Number(res.TownshipNo)
          this.editData = res
          // for (const item of this.editData.proposerdetailhouses) {
          //   this.editData.StrLiveHousingArea = 0.0
          //   if (this.editData.HousCategory == '自有产权房') {
          //     this.editData.StrLiveHousingArea += Number(item.PropertyOwnArea)
          //   } else {
          //     this.editData.StrLiveHousingArea += Number(item.PublicArea)
          //   }
          // }
          // this.editData.StrLiveHousingArea = this.editData.StrLiveHousingArea.toFixed(2)
          // this.editData.proposerdetail[0].isapplicant = true
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleTabChange(key) {
      this.activeKey = key
      const index = this.tabList.findIndex((e) => e.key === key)
      this.tabClick[index] = true
    },
    handleSubmit(e) {
      const infoSumbit = this.$refs.info.handleSubmit()
      const reportSumbit = this.$refs.report.handleSubmit()
      Promise.all([infoSumbit, reportSumbit])
        .then((res) => {
          const data = cloneDeep(this.editData)
          Object.assign(data, res[0], res[1], {
            // ApplyNO: this.editData.ApplyNO || '',
            // ID: this.editData.ID || '',
            LastAlterUserID: this.$store.getters.userid,
            // Builder: this.$store.getters.userid,
            // proposerdelete: this.editData.proposerdelete || '',
          })
          this.$loading.show({
            tip: '提交中，请稍后...',
          })
          data.proposerdetail.forEach((element) => {
            delete element.LiveDistrictAddressArr
            delete element.censusRegister
            if (['低保', '低收入'].includes(element.IfLowObjects)) {
              element.IfLowObjects = '有'
            } else {
              element.IfLowObjects = '无'
            }
            if (Array.isArray(element.GroupOfApplicants)) {
              element.GroupOfApplicants = element.GroupOfApplicants.join(',')
            }
          })
          const { HousCategory, proposerdetailhouses, proposerdetail } = data
          // const idCard = proposerdetail.find((e) => Number(e.Relation) === 0).IDCards
          const IDCardArr = []
          for (let i = 0; i < proposerdetail.length; i++) {
            IDCardArr.push(proposerdetail[i].IDCards)
          }
          console.log('proposerdetail', IDCardArr)

          getHousesCount({
            idcards: IDCardArr.join(','),
            count: HousCategory === '承租公房' || HousCategory === '自有产权房' ? proposerdetailhouses.length || 0 : 0,
          })
            .then((resHouse) => {
              const state = resHouse[0].state
              if (state === '1') {
                if (data.ApplyClass === '低保' && data.ClassName == 570) {
                  getSubsistenceAllowance({
                    idcards: data.IDCard,
                  }).then((res) => {
                    if (res[0].state !== '1') {
                      this.$loading.hide()
                      this.$message.error('当前不存在低保成员，请检查后重新提交')
                    } else {
                      postApplication({
                        ProposerModules: data,
                        State: 'update',
                      })
                        .then((res) => {
                          this.submitSuccess = true
                          this.$eventBus.$emit('cityAuditRefresh')
                        })
                        .finally(() => {
                          localStorage.setItem(
                            'browserCacheEdit',
                            JSON.stringify({
                              id: JSON.parse(localStorage.getItem('browserCacheEdit')).id,
                              isCity: false,
                            })
                          )
                          this.$loading.hide()
                        })
                        .catch((err) => {
                          this.$message.error({
                            text: err,
                          })
                        })
                    }
                  })
                } else {
                  console.log('Please', data)
                  postApplication({
                    ProposerModules: data,
                    State: 'update',
                  })
                    .then((res) => {
                      this.submitSuccess = true
                      this.$eventBus.$emit('cityAuditRefresh')
                    })
                    .finally(() => {
                      this.$loading.hide()
                    })
                    .catch((err) => {
                      this.$message.error({
                        text: err,
                      })
                    })
                }
              } else {
                this.$notification['error']({
                  message: '错误',
                  description: resHouse[0].msg,
                  style: {
                    color: '#000',
                  },
                })
              }
            })
            .finally(() => {
              this.$loading.hide()
            })
        })
        .catch((err) => {
          this.$message.error({
            text: err,
          })
        })
    },
    handleClose() {
      localStorage.setItem(
        'browserCacheEdit',
        JSON.stringify({
          id: JSON.parse(localStorage.getItem('browserCacheEdit')).id,
          isCity: false,
        })
      )
      this.$multiTab.closeCurrentPage()
    },
  },
}
</script>
<style lang="less" scoped></style>
